package com.feature.core.rabbitmq;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.CorrelationDataPostProcessor;

import com.feature.core.util.TraceIdUtil;
import com.feature.core.util.UuidUtil;

/**
 * 在消息发送之前对 CorrelationData 进行后置处理。CorrelationData 主要用于在消息发送时关联消息的唯一标识，结合 RabbitMQ 的消息确认机制（发布确认和返回确认），可以追踪消息的发送状态。
 * 
 * @Description:
 * @author wangzhiyue
 * @date 2025/04/29 09:51:09
 */
public class BeforeSendDataPostProcessor implements CorrelationDataPostProcessor {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public CorrelationData postProcess(Message message, CorrelationData correlationData) {
        MessageProperties messageProperties = message.getMessageProperties();
        messageProperties.setTimestamp(new Date());
        String traceID = TraceIdUtil.getTraceId();

        try {
            InetAddress netAddress = InetAddress.getLocalHost();
            messageProperties.getHeaders().put("sendNetAddress", netAddress);
            messageProperties.getHeaders().put("traceID", traceID);
        } catch (UnknownHostException e) {
            this.logger.warn("获取本地IP出现异常，MSG:{}", e);
        }
        String msgID = message.getMessageProperties().getMessageId();
        if (StringUtils.isEmpty(msgID)) {
            msgID = UuidUtil.getSimpleUUID();
            message.getMessageProperties().setMessageId(msgID);
        }
        if (correlationData == null) {
            correlationData = new CorrelationData(msgID);
        }
        return correlationData;
    }

}
